;; host/posix.scm - (c) rohan drape, 2001-2005

(module 
 posix mzscheme

(require "srfi.scm"
	 (lib "process.ss")
	 (all-except (lib "file.ss") call-with-output-file*))

(provide (all-from (lib "process.ss"))
	 (all-from (lib "file.ss")))

;; Must provide 'system' to execute a string using the host command
;; interpreter and evaluates to the exit status of the command.

;; Must provide 'stat?' to tell if a file system entry exists.

(define (stat? n) (or (file-exists? n) (directory-exists? n)))

;; Must provide 'popen' to open a pipe to a subprocess executing a
;; string command.  The direction is specified by a string mode.

(define (popen command mode)
  (receive 
   (s o i e) (subprocess #f #f #f "/bin/sh" "-c" command)
   (close-input-port e)
   (if (string=? mode "r")
       (begin (close-output-port i)
	      o)
       (begin (close-input-port o)
	      i))))

;; Must provide 'pclose' to close an open pipe.  NOTE: This should
;; wait for the process to exit and return the exit status.

(define (pclose port)
  (close-input-port port))

;; Must provide 'getcwd' to evaluates to the absolute name of the
;; current working directory.  This is the directory relative
;; file-names are resolved against.

(define (getcwd) 
  (path->string (current-directory)))

;; Must provide 'unlink' to delete a named file.

(define unlink delete-file)
(define (unlink* n) (if (stat? n) (unlink n)))

;; Must provide 'getenv' to read the value of a string nameing an
;; environment variable.  Environment variables are strings.  If
;; `name' is not defined evaluates to '#f'.

;; Must provide 'tmpnam' to evaluate to a file name not in use at the
;; time of the call.

(define (tmpnam)
  (let ((file-name (path->string (make-temporary-file))))
    (unlink file-name)
    file-name))

;; Must provide 'rename' to change the name of a file.

(define (rename a b) (rename-file-or-directory a b #t))
(define (rename* a b) (if (and (stat? a) (not (stat? b))) (rename a b)))

;; Must provide 'mkdir' to create a new directory from a string
;; `pathname' with permission defined by an integer `mode'.  NOTE: The
;; `mode' argument is ignored.

(define (mkdir pathname mode)
  (make-directory pathname))

;; Must provide 'mkdir*' to create a new directory and as many
;; intermediary directories as are required.

(define (mkdir* pathname mode)
  (make-directory* pathname))

(provide (all-defined)))
